package com.sdx.console.promote.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdx.common.entity.DictBusiness;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.system.service.DictBusinessService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.promote.entity.*;
import com.sdx.console.promote.service.*;
import com.sdx.console.promote.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * 宣传材料 接口
 */
@RequestMapping("/promote/promoteMaterial")
@Controller
public class PromoteMaterialController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(PromoteMaterialController.class);
    private static final String MODEL = "/promote/promoteMaterial";


    @Resource
	private PromoteMaterialService promoteMaterialService;

	@Resource
	private ResCloudFileService resCloudFileService;

	@Autowired
	private DictBusinessService dictBusinessService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
		List<DictBusiness> moduleList = dictBusinessService.getModule();
		view.addObject("moduleList",moduleList);
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("promote.promoteMaterial.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("promote.promoteMaterial.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer materialId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        PromoteMaterial promoteMaterial = promoteMaterialService.queryById(materialId);
        view.addObject("promoteMaterial", promoteMaterial);
		setPageParam(view,request);
		try {
			view.addObject("promoteMaterialJson", JacksonUtils.toJsonString(promoteMaterial,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("promote.promoteMaterial.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("promote.promoteMaterial.query")
    @ResponseBody
    public JsonResult<PageQuery> list(PromoteMaterial condtion,HttpServletRequest request)
    {
        CoreUser user = getLoginUser(request);
        condtion.setTenantId(user.getTenantId());
        PageQuery page = condtion.getPageQuery();
        promoteMaterialService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,PromoteMaterial promoteMaterial,HttpServletRequest request
							,MultipartFile posterFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/promote/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(posterFile)) {
			try
			{
		        String posterFileNamePair = FileUtils.upload(subPath,posterFile);
		        String posterStoreFile = posterFileNamePair.split("::")[0];
		        posterStoreFile = subPath+posterStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+posterStoreFile,bucketName,posterStoreFile.substring(1));
				String posterUrl = "https://sdxcomm."+ ConfigService.ossDomain+posterStoreFile;
				promoteMaterial.setPoster(posterUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,posterStoreFile,posterUrl,"a","宣传图片");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			promoteMaterial.setTenantId(user.getTenantId());
			promoteMaterial.setCreatedBy(user.getId().intValue());
			promoteMaterial.setCreatedName(user.getName());
			promoteMaterial.setCreatedTime(new Date());
			promoteMaterial.setUpdatedBy(user.getId().intValue());
			promoteMaterial.setUpdatedName(user.getName());
			promoteMaterial.setUpdatedTime(new Date());
			promoteMaterialService.save(promoteMaterial);
		} else {
			promoteMaterial.setUpdatedBy(user.getId().intValue());
			promoteMaterial.setUpdatedName(user.getName());
			promoteMaterial.setUpdatedTime(new Date());
			promoteMaterialService.updateTemplate(promoteMaterial);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("promote.promoteMaterial.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)PromoteMaterial promoteMaterial,HttpServletRequest request
							,@RequestParam("posterFile") MultipartFile posterFile
		)
    {

        return save(true,promoteMaterial,request
					,posterFile
		);
    }

    @PostMapping("/update.json")
    @Function("promote.promoteMaterial.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  PromoteMaterial promoteMaterial,HttpServletRequest request
							,@RequestParam("posterFile") MultipartFile posterFile
		) {
		return save(false,promoteMaterial,request
		,posterFile
		);
    }


   
    @GetMapping("/view.json")
    @Function("promote.promoteMaterial.query")
    @ResponseBody
    public JsonResult<PromoteMaterial>queryInfo(Integer materialId) {
        PromoteMaterial promoteMaterial = promoteMaterialService.queryById( materialId);
        return  JsonResult.success(promoteMaterial);
    }

    @PostMapping("/delete.json")
    @Function("promote.promoteMaterial.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        promoteMaterialService.batchDelPromoteMaterial(idList);
        return JsonResult.success();
    }
    

}
